<template>
  <div class="form__wrapper">
    <el-form :model="formData" :rules="formRules" ref="form" label-width="100px" class="demo-dynamic">
      <el-form-item prop="manufacturer" label="生产厂家" >
        <el-input v-model="formData.manufacturer"></el-input>
      </el-form-item>
      <el-form-item prop="orderName" label="订单名称">
        <el-input v-model="formData.orderName"></el-input>
      </el-form-item>
      <el-form-item
        v-for="(production, index) in formData.productList"
        :label="'产品' + (index + 1)"
        :key="production.key"
        :rules="[
          { required: true, message: '产品不能为空', trigger: ['blur', 'change'], type: 'number' },
        ]"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item
              :prop="'productList.' + index + '.productId'"
              :rules="[
                { required: true, message: '产品不能为空', trigger: ['blur', 'change'], type: 'number' },
              ]"
            >
            <el-select v-model="production.productId" @change="handleProductIdChange(index)">
              <el-option
                v-for="(p, i) in productionOpts"
                :key="i"
                :label="p.name"
                :value="p.id"
                :disabled="disabledProductionIdList.includes(p.id)"></el-option>
            </el-select>
          </el-form-item>
          </el-col>
          <el-col :span="7" :offset="1">
            <el-form-item
              :prop="'productList.' + index + '.amount'"
              :rules="[
                { required: true, message: '产品数量不能为空', trigger: ['blur', 'change'], type: 'number' },
              ]"
            >
              <el-input-number v-model="production.amount" :min="1" :max="99999999"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button class="deleteButton" @click.prevent="removeProduction(production)" size="mini" type="danger">删除</el-button>

          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item>
        <el-button @click="appendProduction" class="appendButton" plain>添加产品</el-button>
      </el-form-item>
    </el-form>
    <div class="actions">
      <el-button type="primary" size="small" @click="submit" :loading="submitLoading">提交</el-button>
      <el-button type="default" size="small" @click="cancel" :disabled="submitLoading">取消</el-button>
    </div>
  </div>
</template>

<script>

import { dict_productionType } from '@/utils/dictionary'

import { createApi } from '@/api/modules/order'
import { dict_productionApi } from '@/api/modules/dictionary'

export default {
  name: 'OrderCreate',
  data () {
    return {
      productionOpts: [],

      disabledProductionIdList: [], // 存放禁用的产品ID，用户选择后，设置为禁用，防止重复选择
      formData: {
        productList: [
          {
            productId: null,
            amount: 1,
            key: Date.now()
          }
        ],
        manufacturer: ''
      },

      formRules: {
        manufacturer: [
          { required: true, message: '生产厂家不能为空', trigger: ['blur', 'change'] },
          { max: 50, message: '生产厂家不能超过50个字符', trigger: ['blur', 'change'] },
        ],
        orderName: [
          { required: true, message: '订单名称不能为空', trigger: ['blur', 'change'] },
          { max: 50, message: '订单名称不能超过50个字符', trigger: ['blur', 'change'] },
        ]
      },

      submitLoading: false
    }
  },
  methods: {
    async getProductionOpts () {
      try {
        const { data } = await dict_productionApi()
        this.productionOpts = data
      } catch (err) {}
    },

    handleProductIdChange(index) {
      this.updateDisabledProductionIdList()
    },
    // 更新禁用的产品ID
    updateDisabledProductionIdList () {
      const disabledProductionIdList = []
      this.formData.productList.forEach(production => {
        disabledProductionIdList.push(production.productId)
      })
      this.disabledProductionIdList = disabledProductionIdList
    },

    
    submit () {
      
      this.$refs['form'].validate(async valid => {
        if(valid) {
          try {
            this.submitLoading = true
            const params = {
              ...this.formData
            }
            await createApi(params)
            this.$message({ type: 'success', message: '添加成功' })
            this.$emit('success')
          } catch (err) {
            console.error(err)
          }
          this.submitLoading = false
        }
      })
    },
    cancel () {
      this.$emit('close')
    },


    removeProduction(item) {
      if(this.formData.productList.length < 2) {
        this.$message.warning('请至少设置一个产品')
        return
      }


      var index = this.formData.productList.indexOf(item)
      if (index !== -1) {
        this.formData.productList.splice(index, 1)
      }

      
      this.updateDisabledProductionIdList()
    },
    appendProduction() {
      this.formData.productList.push({
        productId: null,
        amount: 1,
        key: Date.now()
      })
    }
  },
  mounted () {
    this.getProductionOpts()
  }
}
</script>

<style lang="less" scoped>
@import '../../styles/form.less';

.form__wrapper {
  .el-form, .actions {
    max-width: 500px;
    .el-form-item {
      position: relative;
      .appendButton {
        width: 100%;
      }
      .deleteButton {
        position: absolute;
        right: -70px;
        top: 50%;
        transform: translateY(-50%);

      }
    }
  }
}
</style>